import {
  url_config
} from './config.js'
import ui from '../utils/index.js'
import md5 from '../utils/md5.js'

export const myRequest = (url, method, data, type = false) => {
	if (!type) {
	  if (data) {
	    data['token'] = ui.getStorage('token') || 'none'
	  } else {
	    data = {
	      'token': ui.getStorage('token') || 'none'
	    }
	  }
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: url_config + url,
			method: method.toUpperCase(),
			data: Object.assign(data, getBodyData()),
			dataType: 'json',
			headers: {
			    'Content-Type': 'application/json;charset=UTF-8',
			},
			success: (res) => {
				resolve(res.data)
			},
			fail: (err) => {
				console.log(err)
				reject(err)
			}
		})
	})
}

const appid = '21210416'
const secret = 'ykzc'

function getBodyData() {
  let times = new Date().getTime().toString()
  let ranstr = ui.generateRandomAlphaNum(16).toString()
  let str = appid + times + ranstr
  let sign = md5.hex_md5(md5.hex_md5(str) + secret)
  let data = {
    sign,
    appid: appid,
    secret: secret,
    times: times,
    ranstr: ranstr
  }
  return data
}